<template>
<div>

<!--  选择平台对话框  -->
 <el-dialog
    title="请选择平台"
    :visible.sync="loginVisible"
    width="40%"
    :before-close="handleClose">
        <span>
          <div class="wrap" v-for="(item,index) in platformList"
               style="display: inline-block;margin-left: 20px;user-select: none;"  :key="index" >
            <div :class="item.id === checkPlatform.id ? 'clickIconBorderSty' : 'iconBorderSty' "
                 @click="clickPlatForm(item)">
              <img class="iconSty"
                   :src="require('@/assets/media/' + item.platformCode + '.png' )" >
                 <div class="formNameSty"> {{ item.platformName}}</div>
            </div>
          </div>
        </span>
       <span slot="footer" class="dialog-footer">
<!--         <span style="font-size: 13px;position: absolute;left: 20px">可添加账号 <b style="color: #5b5b5b;margin-left: 5px">10/50</b></span>-->
        <el-button @click="loginVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleClickLoginAccount">确 定</el-button>
      </span>
  </el-dialog>


<!--  登录页  -->
  <el-dialog width="90%"
             style="border-radius: 30px !important;height: calc(100vh - 26px)!important;overflow: hidden!important;padding: 0px 10px !important;"
             :visible.sync="loginStatus" destroy-on-close :before-close="handleClose">
<!--    <div>{{checkPlatform.url}}</div>-->
    <div style="padding: -10px">


    <div style="color: #de9060;margin-left: 39%;font-size: 15px">{{ '请通过手机' +  checkPlatform.platformName + '扫码登录'}}</div>
    <div style="position: relative;" v-loading="loading">
      <div class="nav">

        <i class="el-icon-back icon topIconSty"  @click="handleClickLeft"></i>
        <i class="el-icon-right icon topIconSty" style="margin-left: 10px;" @click="handleClickRight"></i>
        <i class="el-icon-refresh-right icon topIconSty" style="margin-left: 10px;" @click="handleClickReload"></i>
<!--        <div class="link">当前登入平台:{{ checkPlatform.platformName }},登入剩余时间:<strong style="color: #ffe100;"> {{ count }} </strong>秒</div>-->
<!--        <el-link type="primary" class="rightbt" style="float:right">清空缓存</el-link>-->
      </div>
      <div >
        <webview class="webview"
                 ref="webviewBrowser"
                 partition="persist:login"
                 :src="checkPlatform.url"
                 allowpopups
                 useragent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"
                 nodeintegration></webview>
      </div>
    </div>
    </div>
  </el-dialog>
</div>
</template>

<script>
import {Message} from "element-ui";
import { ipcApiRoute } from '@/api/main'
import { ExecuteFunc,formatCode } from "@/utils/execute"
import CookieMixin from '@/layout/mixin/useCookie'
import { addAccount } from "@/api/media/mediaAccount";
import { v4 as uuidv4 } from 'uuid';
export default {
  mixins: [CookieMixin],
  props: {
    addAccountVisible: {
      type: Boolean,
      default: false
    },
    loginVisibleParent: {
      type: Boolean,
      default: false
    },
    platformList:{
      type: Array,
      default: []
    }
  },
  name: "index",
  data(){
    return{
      webview:undefined,
      count: 60 * 10,
      // url:"about:blank",
      checkPlatform:{
        url: "about:blank",
      },
      userInfo:{
        platformCode:undefined, //平台类型
        scanRandom:undefined, //扫码随机数
        systemUniqId:undefined, //系统唯一id
        nickname:undefined, //账号昵称
        headImgUrl:undefined, //账号头像
        cookies:undefined, //登录参数
        uniqId:undefined, //唯一id
        finderUserName:'', //账号唯一标识
        acctType:'' //账号类型
      },
      loading:false,
      loginStatus:false,
    }
  },

  computed: {
    loginVisible: {
      get: function () {
        return this.loginVisibleParent
      },
      set: function (newValue) {
        this.$emit('update:loginVisibleParent', newValue) // 触发更新事件，父组件的showDialog会自动更新
      }
    }
  },
  methods:{

    init(){
      this.webview = this.$refs.webviewBrowser
      this.webview.addEventListener('dom-ready', () => {
        this.webview.setZoomFactor(0.9);
      })
    },


    //登录方法
   async handleClickLoginAccount() {
     console.log(this.checkPlatform)
     if(!this.checkPlatform.id){
       Message.error("请选择要登录的平台!")
       return;
     }
      this.loginVisible = false
      this.loginStatus = true
      this.$nextTick(async ()=>{
        this.count = 60 * 10
        this.loading = true
        this.init()
        //清除cookies
        //await this.useRemoveCookies(this.checkPlatform.url, "persist:login")
        await this.useSleep(2000)
        this.loading = false
        await this.loginAccount()
      })
    },


    /**
     * 扫码轮询获取状态
     * @returns {Promise<void>}
     */
    async  loginAccount(){
      this.count --
      let platform = this.checkPlatform;
      if(this.count > 0){
        const resStatus = ExecuteFunc[platform.platformCode].getLoginStatus;
        let logStatus = await this.webview.executeJavaScript(resStatus);
        console.log(logStatus)
        if (logStatus) {
          const cookies = await this.useGetCookies(this.url, "persist:login")
          let cookieList =   cookies.data.list;
          if(platform.platformCode === 'wxsph'){
            cookieList = cookieList.filter((item)=>{
              return item.name === "sessionid";
            });
          }
          const userInfoRes = await this.webview.executeJavaScript(ExecuteFunc[platform.platformCode].getUserInfo)
          this.userInfo.cookies = JSON.stringify(cookieList);
          this.userInfo.platformCode = platform.platformCode
          //公众号
          const uuid = uuidv4();
          this.userInfo.scanRandom = uuid;
          if(platform.platformCode === 'wxgzh'){
            this.userInfo.systemUniqId = platform.platformCode + userInfoRes.uin_base64
            this.userInfo.headImgUrl = userInfoRes.avatar
            this.userInfo.nickname = userInfoRes.nick_name
            this.userInfo.uniqId = userInfoRes.uin_base64
            // this.userInfo.acctType = userInfoRes.acctType
            await addAccount(this.userInfo).then( res =>{
              console.log(res)
            })
          }
          //视频号
          else if(platform.platformCode === 'wxsph'){
            console.log(userInfoRes)
            for(let i = 0 ; i < userInfoRes.length; i++){
              this.userInfo.systemUniqId = platform.platformCode + userInfoRes[i].uniqId
              this.userInfo.headImgUrl = userInfoRes[i].headImgUrl
              this.userInfo.nickname = userInfoRes[i].nickname
              this.userInfo.uniqId = userInfoRes[i].uniqId
              this.userInfo.acctType = userInfoRes[i].acctType
              this.userInfo.finderUserName = userInfoRes[i].finderUsername
              await addAccount(this.userInfo).then( res =>{
                console.log(res)
              })
            }
          }
          //视频号加热平台
          else if(platform.platformCode === 'wxsphjr'){
            this.userInfo.systemUniqId = platform.platformCode + userInfoRes.username
            this.userInfo.headImgUrl =  userInfoRes.headImgUrl
            this.userInfo.nickname = userInfoRes.nickName
            this.userInfo.acctType = 1
            this.userInfo.finderUserName = userInfoRes.username
            await addAccount(this.userInfo).then( res =>{
              console.log(res)
            })
          }
          //微信小程序
          else if(platform.platformCode === 'wxxcx'){
            this.userInfo.systemUniqId = platform.platformCode + userInfoRes.appid
            this.userInfo.headImgUrl =  userInfoRes.avatar
            this.userInfo.nickname = userInfoRes.nickname
            this.userInfo.uniqId = userInfoRes.fakeIdBase64
            this.userInfo.acctType = 1
            await addAccount(this.userInfo).then( res =>{
              console.log(res)
            })
          }
          //小红书
          else if(platform.platformCode === 'xhs'){
            this.userInfo.systemUniqId = platform.platformCode + userInfoRes.userId
            this.userInfo.headImgUrl =  userInfoRes.userAvatar
            this.userInfo.nickname = userInfoRes.userName
            this.userInfo.uniqId = userInfoRes.userId
            this.userInfo.acctType = 1
            await addAccount(this.userInfo).then( res =>{
              console.log(res)
            })
          }
          //抖音账号
          else if(platform.platformCode === 'douyin'){
            this.userInfo.systemUniqId = platform.platformCode + userInfoRes.uid
            this.userInfo.headImgUrl =  userInfoRes.avatar_larger.url_list[0]
            this.userInfo.nickname = userInfoRes.nickname
            this.userInfo.uniqId = userInfoRes.uid
            this.userInfo.acctType = 1
            await  addAccount(this.userInfo).then( res =>{
              console.log(res)
            })
          }
          //视频号小店
          else if(platform.platformCode === 'sphxd'){
            this.userInfo.systemUniqId = platform.platformCode + userInfoRes.appid
            this.userInfo.headImgUrl =  userInfoRes.iconUrl
            this.userInfo.nickname = userInfoRes.nickName
            this.userInfo.uniqId = userInfoRes.appid
            this.userInfo.acctType = 1
           await addAccount(this.userInfo).then( res =>{
              console.log(res)
            })
          }
          await this.useRemoveCookies(platform.url, "persist:login")
          this.loginStatus = false
          this.$emit("loadData")
          this.$modal.msgSuccess("账号添加成功！")
        }else{
          await this.useSleep(500)
          await this.loginAccount()
        }
      }
    },





    //关闭对话框
    handleClose(){
      this.loginVisible = false
      this.loginStatus = false
      this.checkPlatform = []
    },
    /**
     * 选中平台
     */
    clickPlatForm(item){
      this.checkPlatform = item
    },
    //后退
    handleClickLeft(){
      this.$refs.webviewBrowser.goBack()
    },
    //前进
    handleClickRight(){
      this.$refs.webviewBrowser.goForward()
    },
    //刷新
    handleClickReload(){
      this.$refs.webviewBrowser.reload()
    }
  }
}
</script>

<style lang="scss" >

.el-dialog__header {
  padding: 20px !important;
  padding-bottom: 10px !important;
}

.el-dialog__body{
  padding: 0px 20px;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
}

.wrap{
  overflow-x: auto;
  overflow-y: hidden;
  white-space: nowrap;
}

.iconSty{
  width: 35px;
  height: 35px;
  top: 11%;
  position: relative;
  margin-left: 15px
}

.iconBorderSty{
  cursor: pointer;
  border: 1px solid #f1f1f1;
  display: flex;
  width: 135px;
  border-radius: 10px;
  height: 50px;
  transition: transform .3s;
}
.clickIconBorderSty{
  cursor: pointer;
  border: 1px solid #f1f1f1;
  display: flex;
  width: 135px;
  border-radius: 10px;
  height: 50px;
  box-shadow: 0 0 30px 30px #2b7bf3;
  transition: transform .3s;
}
.nav{
  margin-bottom: 10px;
}
.topIconSty{
  cursor: pointer;
  font-size: 20px;
  color: #646464;
}

.topIconSty:hover{
  color: #2860f1;
}


.formNameSty{
  margin-left: 10px;
  line-height: 50px;
  font-size: 12px
}

.webview{
  height: calc(100vh - 157px);
  width: 100%;
}
</style>
